
const path = require('path');
const log4js = require('log4js');
const logDir = path.join(__dirname,'logs');

function initLogger(options){
    log4js.configure({
        appenders: {
            out: {
                type: 'stdout'
            },
            access: {
                type: 'dateFile',
                filename: path.join(logDir,'access.log'),
                alwaysIncludePattern:true,
                compress:true,
                keepFileExt:true,
            },
            errs:{
                type:'file',
                filename:path.join(logDir,'errs.log'),
                compress:true,
                maxLogSize:5 * 1024 * 1024, // 5M
                backups:5,
            }
        },
        categories: {
            access: {
                appenders: ['access'],
                level: 'info'
            },
            default: {
                appenders: ['out'],
                level:'debug'
            },
            errs:{
                appenders:['errs'],
                level:'error'
            }
        }
    });
    options.accessLogger = log4js.getLogger('access');
    let defaultLogger = options.defaultLogger = log4js.getLogger();
    options.errLogger = log4js.getLogger('errs');
    defaultLogger.info('initLogger...');
}

const logger = function(app,name){

    if(app[name]){
        let msg = `already has key:${name} in app.`;
        throw new Error(msg);
    }

    let options = app[name] = {};
    initLogger(options);

    return async (ctx,next)=>{
        options.accessLogger.info('doing url:' + ctx.request.url);
        let start = Date.now();
        await next();
        let spendTime = Date.now() - start;
        options.accessLogger.info(`process url:${ctx.request.url} spendTime:${spendTime}ms`);
    }
};

module.exports = logger;
